package com.kerrykidz.common.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.service.ICommonService;
import com.kerrykidz.dao.model.SysAttFileEntity;
import com.kerrykidz.membership.dao.model.CusMemEntity;
import com.kerrykidz.membership.service.IMemberService;
import com.kerrykidz.system.dao.model.SecUsrEntity;
import com.kerrykidz.system.dao.model.SysParaEntity;
import com.kerrykidz.system.util.UserUtil;
import com.rdp.framework.exception.RDPException;

@Controller
@RequestMapping("common")
public class CommonController {

	@Autowired
	private ICommonService commonService;

	@Autowired
	private IMemberService memberService;

	private Logger logger = Logger.getLogger(CommonController.class);

	/**
	 * 取得经理身份
	 * 
	 * @param password
	 *            经理密码
	 * @param session
	 * @return
	 * @throws Exception
	 * @date: 2014年8月21日
	 */
	@RequestMapping(value = "validateManager", method = RequestMethod.POST)
	@ResponseBody
	public SecUsrEntity validateManager(
			@RequestParam("password") String password, HttpSession session)
			throws Exception {
		SecUsrEntity user = this.commonService.findDiscountUser(password,
				UserUtil.getUserFromSession().getBranId());
		this.logger.info("获取经理信息");
		return user;
	}

	/**
	 * 显示图片
	 *  
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/showImage")
	public void showImage(@RequestParam(value = "imagePath") String imagePath,
			HttpServletResponse response) throws ServletException, IOException {
		// 以byte流的方式打开文件
		SysParaEntity para = commonService
				.findSysParaById(Constants.SYS_BASE_PATH_IMAGE);
		String basePath = null;
		if (para != null) {
			basePath = para.getParaValue();
		}
		FileInputStream hFile = new FileInputStream(basePath + "\\" + imagePath);

		int i = hFile.available(); // 得到文件大小
		byte data[] = new byte[i];
		hFile.read(data); // 读数据
		response.setContentType("image/*"); // 设置返回的文件类型
		OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		toClient.write(data); // 输出数据

		toClient.flush();
		toClient.close();
		hFile.close();
	}

	/**
	 * 获取图片信息
	 * 
	 * @param attfile
	 * @param response
	 * @date: 2014年9月2日
	 */
	@RequestMapping(value = "getImageByAttfile")
	public void getImageByAttfile(@RequestParam("attfileId") String attfile,
			HttpServletResponse response) {
		SysAttFileEntity entity = this.commonService.findAttFileByPk(attfile);
		if (entity != null)
			try {
				showImage(entity.getAttfileName(), response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	/**
	 * 
	 * @Desc 根据会员ID获取会员头像
	 * @author QUINN
	 * @date 2014年9月12日上午10:48:14
	 * @param memId
	 * @param response
	 */
	@RequestMapping(value = "getMemTitle")
	public void getMemTitle(@RequestParam("memId") String memId,
			HttpServletResponse response) {
		try {
			CusMemEntity mem = this.memberService.findMemberById(memId);
			if (mem != null && StringUtils.isNotBlank(mem.getImagePath()))
				showImage(mem.getImagePath(), response);
		} catch (RDPException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "repeatSubmit")
	public String repeatSubmit() {
		return "error";
	}

	/**
	 * 下载附件
	 * 
	 * @param attFile
	 * @param response
	 * @param key
	 *            对应SYS_PARA表KEY值
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/downloadAttFile", method = RequestMethod.POST)
	public void downloadAttFile(
			@RequestParam(value = "attFile") String attFile,
			HttpServletResponse response,
			@RequestParam(value = "key") String key) throws ServletException,
			IOException {

		SysParaEntity para = commonService.findSysParaById(key);
		String basePath = null;
		if (para != null) {
			basePath = para.getParaValue();
		}
		String filpath = basePath + "\\" + attFile;
		File fil = new File(filpath);
		if (fil.exists()) {
			String fileType = attFile.substring(attFile.lastIndexOf(".") + 1);
			if ("pdf".equalsIgnoreCase(fileType)) {
				response.setContentType("application/pdf;charset=UTF-8");
			} else if ("xls".equalsIgnoreCase(fileType)) {
				response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			} else if ("xlsx".equalsIgnoreCase(fileType)) {
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
			} else if ("doc".equalsIgnoreCase(fileType)) {
				response.setContentType("application/msword;charset=UTF-8");
			} else if ("docx".equalsIgnoreCase(fileType)) {
				response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
			}

			//URLEncoder.encode(attFile, "UTF-8")解决中文乱码
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ URLEncoder.encode(attFile, "UTF-8")+"\"");
			response.addHeader("Content-Length", "" + fil.length() + "");
			response.setContentType("application/x-download");

			byte[] buffer = new byte[4096];// 缓冲区
			BufferedOutputStream output = null;
			BufferedInputStream input = null;
			try {
				output = new BufferedOutputStream(response.getOutputStream());
				input = new BufferedInputStream(new FileInputStream(fil));
				int n = -1;
				while ((n = input.read(buffer, 0, 4096)) > -1) {
					output.write(buffer, 0, n);
				}
				output.flush();
				response.flushBuffer();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭流
				if (input != null)
					input.close();
				if (output != null)
					output.close();
			}
		}
	}
}
